package s02;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author wangpp
 */
public class SampleAop implements MethodInterceptor {

    private SampleAdvice advice;

    public SampleAop(SampleAdvice advice) {
        this.advice = advice;
    }

    public static <T> T createInstance(Class<T> clazz, SampleAdvice advice) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new SampleAop(advice));
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object result = null;
        try {
            result = advice.before(obj, method, args, proxy);
            if (result != null) {
                return result;
            }
            result = proxy.invokeSuper(obj, args);

            result = advice.after(obj, method, args, proxy, result);

        } catch (Throwable e) {
            result = advice.error(obj, method, args, proxy, e);
            if (result == null) {
                throw e;
            }
        } finally {
            result = advice.finallyHandle(obj, method, args, proxy, result);
        }

        return result;
    }

}
